# 多阶段构建：前端构建阶段
FROM node:18-alpine AS frontend-builder

WORKDIR /app/frontend

# 复制前端package文件
COPY webapp/package*.json ./

# 安装前端依赖
RUN npm ci --only=production

# 复制前端源代码
COPY webapp/ ./

# 构建前端
RUN npm run build

# 后端构建阶段
FROM maven:3.8.6-openjdk-21-slim AS backend-builder

WORKDIR /app/backend

# 复制Maven配置文件
COPY server/pom.xml ./

# 下载依赖（利用Docker缓存）
RUN mvn dependency:go-offline -B

# 复制后端源代码
COPY server/src ./src

# 构建后端
RUN mvn clean package -DskipTests -B

# 生产运行阶段
FROM openjdk:21-jdk-slim

# 安装nginx和必要工具
RUN apt-get update && apt-get install -y \
    nginx \
    curl \
    supervisor \
    && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 复制后端JAR文件
COPY --from=backend-builder /app/backend/target/queue-admin-*.jar app.jar

# 复制前端构建文件到nginx目录
COPY --from=frontend-builder /app/frontend/dist /usr/share/nginx/html

# 复制nginx配置
COPY docker/nginx.conf /etc/nginx/nginx.conf

# 复制supervisor配置
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# 创建日志目录
RUN mkdir -p /app/logs /var/log/supervisor

# 创建非root用户
RUN groupadd -r appuser && useradd -r -g appuser appuser
RUN chown -R appuser:appuser /app /var/log/supervisor
RUN chown -R www-data:www-data /usr/share/nginx/html

# 暴露端口
EXPOSE 80 8080

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost/health && curl -f http://localhost:8080/actuator/health || exit 1

# 设置环境变量
ENV JAVA_OPTS="-Xmx1g -Xms512m -XX:+UseG1GC -XX:+UseContainerSupport"

# 使用supervisor启动多个服务
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
